<?php
/**
 * Coupons row class
 *
 * This row class uses in the model to represent a Coupons.
 *
 * @access 	public
 * @author 	Rob/Valentin
 * @copyright	ResMania 2009 all rights reserved.
 * @version	1.0
 * @link	http://developer.resmania.com/api
 * @since  	08-2009
 */
class RM_Coupons_Row extends RM_Discounts_Row_Abstract {

    private $_totalAmount = null;

    /**
     * Save total amount that already saved in the resevation (for tax calculation)
     *
     * @param float $total
     * @return void
     */
    public function setTotalAmount($total){
        $this->_totalAmount = $total;
    }

    /**
     * Calculate
     *
     * @param RM_Reservation_Details $detail
     * @return float total amount of discount OR false if discount doesn't match
     */
    public function calculate(RM_Reservation_Details $detail){
        if ($this->_totalAmount !== null) return $this->_totalAmount;
        return parent::calculate($detail);
    }

    /**
     * We need to delete all unit coupons as well.
     *
     * @return void
     */
    public function delete(){
        $model = new RM_UnitCoupons();
        $rows = $model->getByCoupon($this);
        foreach ($rows as $row) {
            $row->delete();
        }
        parent::delete();
    }

    /**
     * Returns the column/value data as an array and parse all assigned units
     * in csv format in 'units' field.
     *
     * @return array
     */
    public function toArray(){
        $dataRow = parent::toArray();
        if ($this->global == 1) {
            $dataRow['units'] = array(0);
        } else {
            $unitCouponsModel = new RM_UnitCoupons();
            $unitIDs = array();
            $unitCoupons = $unitCouponsModel->getByCoupon($this);
            foreach ($unitCoupons as $unitCoupon){
                $unitIDs[] = $unitCoupon->unit_id;
            }
            $dataRow['units'] = implode(',', $unitIDs);
        }
        return $dataRow;
    }

    /**
     * Check if this coupon used by user or not
     *
     * @param RM_User_Row $user
     * @return bool
     */
    public function isUsedBy(RM_User_Row $user){
        if ($user->isGuest()) return false;

        $model = new RM_UserCoupons();
        return $model->isUsed($this, $user);
    }

    public function toString(){
        return RM_Environment::getInstance()->getTranslation(RM_Environment::TRANSLATE_MAIN)->_('Common.Coupons.Main', 'Coupon').': '.$this->_type->toString();
    }
}